package com.epam.debrecen.hackathon.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.commons.io.IOUtils;

import com.epam.debrecen.hackathon.ai.Bot;
import com.epam.debrecen.hackathon.ai.model.GameState;
import com.epam.debrecen.hackathon.ai.model.GameStateImplementation;
import com.epam.debrecen.hackathon.com.InputResolver;

public class BotServer {

	private final Bot bot;
	private final String host;
	private final String pass;

	public BotServer(String pass, String host, Bot bot) throws IOException {
		this.pass = pass;
		this.host = host;
		this.bot = bot;
	}

	public void start() throws NumberFormatException, UnknownHostException, IOException {
		Socket clientSocket = this.createSocket();

		BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
		this.sendAuth(writer);

		try {
			while (true) {
				this.readDataFromServer(writer, reader);
			}
		} catch (Exception e) {
			e.printStackTrace();
			IOUtils.closeQuietly(reader);
			IOUtils.closeQuietly(writer);
		}

	}

	private Socket createSocket() throws UnknownHostException, IOException {
		String[] host_ip = this.host.split(":");
		Socket clientSocket = new Socket(host_ip[0], Integer.valueOf(host_ip[1]));
		return clientSocket;
	}

	private void readDataFromServer(PrintWriter writer, BufferedReader reader) throws IOException {

		GameState gameState = new GameStateImplementation();
		InputResolver inputResolver = new InputResolver();
		StringBuilder builder = new StringBuilder();

		String userInput;
		while ((userInput = reader.readLine()) != null) {

			if (userInput.startsWith("?")) {

				inputResolver.resolveServerMessages(builder.toString(), gameState);

				String response = inputResolver.resolveServerRequest(userInput.trim(), gameState);

				if (response != null) {
					this.writeLnOut(response, writer);
				}

				return;
			} else {
				builder.append(userInput).append("\n");
			}
		}

	}

	private void sendAuth(PrintWriter writer) throws NumberFormatException, UnknownHostException, IOException {
		this.writeLnOut(String.format("AUTH %s", this.pass.trim()), writer);
	}

	private void writeLnOut(String message, PrintWriter writer) throws IOException {
		writer.println(message);
	}
}
